import { createSlice, PayloadAction } from '@reduxjs/toolkit';

interface IState {
  counter: number;
}

// 将 initialState 提取出来可以进行类型的定义
// 解决像 arr : [] 类型推导为 never[] 的问题
const initialState: IState = {
  counter: 100,
};

const counterReducer = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: (state) => {
      // Redux Toolkit 允许我们在 reducers 写 "可变" 逻辑。
      // 并不是真正的改变 state 因为它使用了 immer 库
      // 当 immer 检测到 "draft state" 改变时，会基于这些改变去创建一个新的
      // 不可变的 state
      state.counter += 1;
    },
    decrement: (state) => {
      state.counter -= 1;
    },
    // action : ({ type: 'counter/incrementByAmount', payload: 10 }
    // payload 类型定义
    incrementByAmount: (state, { payload }: PayloadAction<number>) => {
      state.counter += payload;
    },
  },
});
export const { increment, decrement, incrementByAmount } = counterReducer.actions;
export default counterReducer.reducer;
